﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Dapper;
using DotnetSpider.DataFlow;
using DotnetSpider.DataFlow.Parser;
using DotnetSpider.DataFlow.Storage;
using DotnetSpider.Http;
using DotnetSpider.RequestSupplier;
using DotnetSpider.Scheduler.Component;
using DotnetSpider.Selector;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;

using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using Serilog;
using static DotnetSpider.Lawyee.Src.LawSpider;
using StringContent = DotnetSpider.Http.StringContent;

namespace DotnetSpider.Lawyee.Src
{
	public class cprqDataParser : DataParser
	{


		/// <summary>
		/// 根据日期生成 leftDataItem  请求
		/// </summary>
		/// <param name="startDate">开始日期</param>
		/// <param name="totalDays">0代表当天</param>
		/// <returns></returns>
		public static Request ConditionRequst(string startDate, int totalDays = 0)
		{
			Request request = null;
			try
			{
				JObject propertyItem = new JObject();

				propertyItem.Add(new JProperty("key", "cprq"));

				DateTime dtStart = Convert.ToDateTime(startDate);

				DateTime dtEnd = new DateTime();

				dtEnd = dtStart.AddDays(totalDays);

				string dtEndStr = dtEnd.ToString("yyyy-MM-dd");

				propertyItem.Add(new JProperty("value", startDate + " TO " + dtEndStr));

				JArray condition = new JArray();

				condition.Add(propertyItem);

				string conditionText = JsonConvert.SerializeObject(condition);

				//url = "https://2020.ip138.com/";

				request = CreateDocDataItemRequest(conditionText, "cprqDataParser");

				request.SetProperty("conditionText", conditionText);

				request.SetProperty("start", startDate);

				request.SetProperty("totalDays", totalDays.ToString());

			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "cprqDataParser:ConditionRequst:");

				throw ex;
			}

			return request;
		}



		public cprqDataParser()
		{
			AddRequiredValidatorEx("cprqDataParser");
		}

		protected override Task Parse(DataContext context)
		{
			try
			{
				//左边菜单json
				var result = CommonHelper.CommonParser(context);

				if (string.IsNullOrEmpty(result) || !result.StartsWith("{") || !result.EndsWith("}") )
				{
					Console.WriteLine("DocInfoSearch：!{}" + result);
					CommonHelper.RetryRequest(context);
					return Task.CompletedTask;
				}
				else
				{
					JObject dataItemResult = JObject.Parse(result);
					FilterData(context, dataItemResult);
				}

			}
			catch (Exception ex)
			{
				CommonHelper.RetryRequest(context);
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "cprqDataParser:Parse:");

				//throw ex;
			}

			return Task.CompletedTask;

		}


		/// <summary>
		/// 左边菜单列表根据   start   totalDays   生成按每天的左边刷选菜单
		/// </summary>
		/// <param name="context"></param>
		/// <param name="dataItemResult"></param>
		protected static void FilterData(DataContext context, JObject dataItemResult)
		{
			try
			{
				Request request = null;
				//总数
				int count = 0;
				if (dataItemResult.Property("s42") != null && dataItemResult["s42"].GetType() == typeof(JArray))
				{
					JArray jobjTotal = (JArray)dataItemResult["s42"];

					if (jobjTotal.Count > 0)
					{
						foreach (JObject everyYearTotal in jobjTotal)
						{
							count += int.Parse(everyYearTotal["count"].ToString());
						}
					}
				}
				else
				{
					//Console.WriteLine("返回为空："+ dataItemResult.ToJson());
					//throw new Exception("返回为空");
				}
				

				string pageId = context.Request.GetProperty("pageId");

				JArray condition = JArray.Parse(context.Request.GetProperty("conditionText"));

				Dictionary<string, string> properties = context.Request.Properties;

				string startDate = properties["start"];
				if (count > 0)
				{
					using (var conn = new SqlConnection(ConfigurationManager.AppSettings["StorageConnectionStringForDate"]))
					{
						conn.Execute(
						$"update dateOne set totalcount = @totalcount where dateone = @dateone", new { totalcount = Convert.ToInt32(count), dateone = startDate });

					}
				}
				

				if (count == 0)
				{

					//using (var conn = new SqlConnection(ConfigurationManager.AppSettings["StorageConnectionStringForDate"]))
					//{

					//	string MachId = ConfigurationManager.AppSettings["MachId"];
					//	string StartDate = ConfigurationManager.AppSettings["StartDate"];
					//	var dateOne = conn.ExecuteScalar($"select TOP 1  dateOne from dateOne where started = 0  and (totalcount = 0 or totalcount > completed) and (MachId = @MachId ) and dateOne >= @StartDate ORDER BY dateOne asc", new { MachId = MachId, StartDate = StartDate });
					//	List<Request> listRequest = new List<Request>();
					//	Request requestnew = cprqDataParser.ConditionRequst(dateOne.ToString(), 0);
					//	listRequest.Add(requestnew);
					//	context.AddFollowRequests((IEnumerable<Request>)listRequest.ToArray());
					//	conn.Execute($"update dateOne  WITH (TABLOCKX) set started = 1, Pcount = Pcount+1 where dateone = @dateone", new { dateone = dateOne.ToString() });
					//}

				}
				else if (count <= MaxRecord && count > 0)  //小于当前设定值, 无需进行过虑
				{
					//直接查询文书id
					ScrollPage(count, pageId, condition, context);

				}
				else
				{ //解析过虑条件

					int totalDays = int.Parse(context.Request.GetProperty("totalDays"));

					string start = context.Request.GetProperty("start");

					if (totalDays > 0)
					{

						//Dictionary<string, int> dateDict = SplitDate(start, totalDays);
						Dictionary<string, int> dateDict = CommonHelper.SplitDateForDay(start, totalDays);

						foreach (KeyValuePair<string, int> dateItem in dateDict)
						{
							request = ConditionRequst(dateItem.Key, dateItem.Value);
							context.AddFollowRequests(request);
						}


					}
					else  //1天之内还是大于recordmax
					{
						s2DataParser.s2DataParserCreateSubRquest(context, dataItemResult, pageId, condition);

					}
				}

			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "cprqDataParser:FilterData:");
				throw ex;
			}

		}
	}

	




































}
